var blogDao = require('../dao/blog.js');
var check = require('../middlewares/check.js');
module.exports = function(app) {

	app.get('/blog/index/:pageIndex?', function(req, res) {
		var pageIndex = req.params.pageIndex;
		if (typeof pageIndex == 'undefined') {
			pageIndex = 1;
		}
		blogDao.findBlogs(pageIndex, function(isSuccess, err, blogs, count, pageSize) {
			if (isSuccess) {
				res.render('blog/index', {
					blogs: blogs,
					pageIndex: pageIndex * 1,
					dataCount: count,
					pageSize: pageSize,
					pageCount: Math.ceil(count / pageSize)
				});
			} else {
				res.send("<script type='text/javascript'>alert('网络异常,请稍后再试!');history.back(-1);</script>");
			}
		});
	});

	app.get('/blog/edit/:_id?', check.checkLogin, function(req, res) {
		var id = req.params._id;
		if (typeof id == 'undefined') {
			res.render('blog/edit', blogDao.getNullBlog());
		} else {
			blogDao.findBlogById(id, function(isSuccess, blog) {
				if (isSuccess) {
					if (blog != null) {
						res.render('blog/edit', blog);
						return;
					}
				}
				res.send("<script type='text/javascript'>alert('没有该记录!');history.back(-1);</script>");
			});
		}
	});

	app.post('/blog/edit', check.checkLogin, function(req, res) {
		var blog = blogDao.getBlogByJson(req.body);
		blogDao.addOrUpdate(blog, function(isSuccess, blog, action) {
			if (isSuccess) {
				res.redirect('/blog/myblog');
			} else {
				res.send("<script type='text/javascript'>alert('网络异常,请稍后再试!');history.back(-1);</script>");
			}
		});
	});

	app.get('/blog/look/:_id', function(req, res) {
		var id = req.params._id;
		var user_id = '';
		var user_name = '';
		if (typeof req.session.user != 'undefined') {
			user_id = req.session.user._id;
			user_name = req.session.user.name;
		}
		blogDao.readBlog(id, function(isSuccess, blog) {
			if (isSuccess) {
				res.render('blog/look', {
					blog: blog,
					user_id: user_id,
					user_name: user_name

				});
			} else {
				res.send("<script type='text/javascript'>alert('没有该记录!');history.back(-1);</script>");
			}
		});

	});

	app.get('/blog/myblog/:pageIndex?', check.checkLogin, function(req, res) {
		var user_id = req.session.user._id;
		var pageIndex = req.params.pageIndex;
		if (typeof pageIndex == 'undefined') {
			pageIndex = 1;
		}

		blogDao.findBlogsByUserId(pageIndex, user_id, function(isSuccess, err, blogs, count, pageSize) {
			if (isSuccess) {
				res.render('blog/myblog', {
					blogs: blogs,
					pageIndex: pageIndex * 1,
					dataCount: count,
					pageSize: pageSize,
					pageCount: Math.ceil(count / pageSize)
				});
			} else {
				res.send("<script type='text/javascript'>alert('网络异常,请稍后再试!');history.back(-1);</script>");
			}
		});
	});

	app.post('/blog/zan', function(req, res) {
		var id = req.body._id;
		blogDao.zanBlog(id, function(isSuccess, blog) {
			if (isSuccess) {
				res.json({
					status: true,
					blog: blog
				});
			} else {
				res.json({
					status: false,
					blog: null
				});
			}
		});
	});
};